(function () {

    window.$game = {
        init,
        onMsg,
        getRooms,
        enterRoom,
        createRoom,
        quiteRoom,
        ready,
        defeat,
        peace,
        sendChat,
        pickChess,
    }

    /** 棋子设置 */
    let chessColor = "black";
    let isMoveChess = false;

    /** websocket传输的数据 */
    let ws;
    let user = {};
    let room = {};
    let startMoveChessId;

    // 游戏加载，连接服务器
    function init(url, name, token, callback) {
        // 连接游戏服务器，发送‘init’，设置用户连接唯一凭证
        // let gameUrl = 'ws://182.61.38.152/:80';
        // let gameUrl = 'ws://localhost:8081';
        let gameUrl = url;
        return $ws.open(gameUrl).then(res => {
            ws = res;
            user = {
                name,
                token,
            };

            onMsg(callback);

            return $ws.send(ws, 'init', user);
        })
    }

    // 获取房间列表
    function getRooms() {
        return $ws.send(ws, 'rooms', user)
    }

    // 进入房间
    function enterRoom(id) {
        return $ws.send(ws, 'enter', {
            token: user.token,
            room: id,
        })
    }

    // 创建房间
    function createRoom(params) {
        return $ws.send(ws, 'create', {
            token: user.token,
            title: '战个痛快吧',
            ...params
        })
    }

    // 离开房间
    function quiteRoom() {
        return $ws.send(ws, 'out', {
            token: user.token,
            room: room.id
        }).then(r => {
            console.log("你退出来了");
            // 清空房间缓存信息
            room = {};
        })
    }

    //准备
    function ready() {
        $ws.send(ws, 'ready', {
            token: user.token,
            room: room.id
        }).then(r => {
            // 同步游戏设置项
            // 确定棋子颜色:先手黑棋后手白棋
            if (room.user[room.offensive] && user.token == room.user[room.offensive].token) {
                chessColor = "black";
            } else {
                chessColor = "white";
            }
        })
    }

    // 认输
    function defeat() {
        $ws.send(ws, 'defeat', {
            token: user.token,
            room: room.id
        })
    }

    // 和棋
    function peace() {
        $ws.send(ws, 'peace', {
            token: user.token,
            room: room.id
        })
    }

    /**
     * 点击棋子
     */
    function pickChess() {
        // 是否开始，是否轮到你
        if (!room.ready || !room.start || !room.user[room.turn] || user.token !== room.user[room.turn].token) {
            return
        }

        // 获取点击事件对象，棋子的#id， 棋子data-id
        let e = window.event || arguments.callee.caller.arguments[0];
        // let hrefTmp = e.target.href.baseVal;
        let id = e.target.dataset.id;

        // 吃棋阶段
        if (room.eat) {
            eatChess(id)
            return
        }

        // 下棋阶段
        if (room.count <= 9) {
            if (!(room.black.includes(id)) && !(room.white.includes(id))) {
                sendChessId(id);
            }
            return
        }

        // 走棋阶段
        if (room.count > 9) {
            if (!isMoveChess) {
                // 拾起棋子
                if (room[`${chessColor}`].indexOf(id) > -1) {
                    isMoveChess = true;
                    e.target.href.baseVal = "#chess-green";
                    startMoveChessId = id;
                }
            } else {
                // 放下棋子
                // 点击自己的棋子
                if (room[`${chessColor}`].indexOf(id) > -1) {
                    // 重置绿色棋子
                    let tempArr = e.path[1].children;
                    for (let i = 0; i < tempArr.length; i++) {
                        let item = tempArr[i];
                        if (item.tagName == 'use' && item.href.baseVal == "#chess-green") {
                            // item.href.baseVal = "#chess-green";
                            item.href.baseVal = `${'#chess-' + chessColor}`;
                        }
                    }

                    e.target.href.baseVal = "#chess-green";
                    startMoveChessId = id;
                    return
                }

                // 空白棋子，判断是否可以放置
                if (!room.white.indexOf(id) > -1 || !room.black.indexOf(id) > -1) {
                    if (room[`${chessColor}`].length > 3) {
                        if (!checkChessMove(startMoveChessId, id)) {
                            return
                        }
                        isMoveChess = false;
                    }
                    if (room[`${chessColor}`].length <= 3) {
                        // 飞棋：不限制格数
                        isMoveChess = false;
                    }
                    // endMoveChessId = id;

                    /** ********** 发送WS: startMoveChessId endMoveChessId */
                    sendChessId(startMoveChessId + id);
                }
            }
        }
    }

    /**
     * 走棋阶段，只能走一步的规则检测
     * @param {String} start 起始移动的棋子ID
     * @param {String} end 落下棋子的位置ID
     */
    function checkChessMove(start, end) {
        let startCapt = start.substr(0, 1);
        let endCapt = end.substr(0, 1);
        let startNum = Number(start.substr(1, 1));
        let endNum = Number(end.substr(1, 1));

        if (startCapt == endCapt) {
            let numStr = '8123456781';
            if (numStr[startNum - 1] == endNum || numStr[startNum + 1] == endNum) {
                return true
            }
        }

        if (startNum == endNum && (/^[2468]{1}$/.test(startNum))) {
            if (startCapt == 'b' || endCapt == 'b') {
                return true
            }
        }

        // 不能移动
        return false
    }

    /**
     * 
     * @param {String} id 棋子ID
     */
    function eatChess(id) {
        // 棋盘上的棋子
        if (room.black.includes(id) || room.white.includes(id)) {
            sendChessId(id);
        }
    }

    /**
     * 
     * @param {String} chess 棋子ID：单/双
     */
    function sendChessId(chess) {
        let params = {
            token: user.token,
            room: room.id,
            chess
        }
        let method = 'move';
        if (room.eat) {
            method = 'eat';
        }
        $ws.send(ws, method, params)
    }

    /**
     * 发送消息
     * @param {String} method 'one' 'many' 'all'
     * @param {String} msg 发送的消息
     * @param {*} id 私聊对象TOKEN : user.token
     */
    function sendChat(method, msg, id) {

        let data = {
            token: user.token,
            msg,
        }

        if (method == "one") {
            data.toToken = id;
        }

        if (method == "many") {
            data.room = room.id
        }

        $ws.send(ws, method, data)
    }

    /**
     * 获取数据后，总接口
     * @param {String} data WebSocket接收的数据字符串
     */
    function onMsg(callback) {
        $ws.onMsg(ws, r => {
            console.log(r);
            switch (r.method) {
                case 'init':
                    user = r.data;
                    break;
                case 'enter':
                case 'ready':
                case 'start':
                case 'move':
                case 'eat':
                case 'out':
                    room = r.data;
                    break;
                case 'defeat':
                case 'winner':
                    room = r.data;
                    let temp = r.data;
                    if (temp.user[temp.offensive] && user.token == temp.user[temp.offensive].token) {
                        chessColor = 'black';
                    } else {
                        chessColor = 'white';
                    }
                    break;
            }
            callback(r);
        })
    }
})()